<template>
    <div class="login-modal">
        <div class="mask" @click="chanIsShowLoginModalA(false)"></div>
        <div class="login-box">
            <img @click="chanIsShowLoginModalA(false)" class="close" src="@/assets/img/close.png" alt="">
            <ul class="title">
                <li :class="isShowForm?'active':''" @click="isShowForm=true">手机号登录</li>
                <li>|</li>
                <li :class="!isShowForm?'active':''" @click="weixinClick">微信扫码登录</li>
            </ul>
            <div class="body">
                <div class="form" v-show="isShowForm">
                    <div class="input-group">
                        <input type="number"  placeholder="请输入手机号" v-model.trim="phoneNum">
                    </div>
                    <div class="input-group">
                        <slide-verify :l="42" :r="20" :w="360" :h="140" @success="onSuccess" @fail="onFail" @refresh="onRefresh" :style="{ width: '100%' }" class="slide-box" ref="slideBlock" :slider-text="msg"></slide-verify>
                    </div>
                    <div class="input-group">
                        <input type="text" placeholder="请输入验证码" v-model.trim="SMSCode">
                        <div class="btn get-code" >
                            <span v-show="!isShowCount" @click="getSMScode">获取验证码</span>
                            <span v-show="isShowCount">{{count}}s</span>
                        </div>
                    </div>
                    <div class="btn" @click="submitLogin">登录</div>
                </div>
                <div id="weixin" class="qrcode" v-show="!isShowForm">二维码</div>
            </div>
        </div>
        
    </div>
</template>

<script>
import { mapMutations ,mapActions} from 'vuex'
import {SendSMSAPI,PhoneReginAPI,bingPhoneAPI} from "@/request/api"
import {validatePhoneNum} from "@/utils/index"
export default {
    data () {
        return {
            //是否展示表单
            isShowForm:true,
            //滑块验证码的文本提示
            msg: "向右滑动",
            //输入的手机号
            phoneNum:"",
            //输入的验证码
            SMSCode:"",
            //倒计时的数字
            count:60,
            maxCount:60,
            //是否展示倒计时
            isShowCount:false,
            //倒计时的定时器
            timer:null
        }
    },
    methods:{
        ...mapMutations({
            chanIsShowLoginModalA:'ShowLoginModal/chanIsShowLoginModal',
            chanIsShowCart:'LoginStatus/chanIsShowCart'
        }),
        ...mapActions({
            asyncChanIsShowToast:'ToastStatus/asyncChanIsShowToast',
            asyncCharUserInfo:'UserInfo/asyncCharUserInfo'
        }),
        weixinClick(){
            //切换到二维码显示框
            this.isShowForm=false
            // 申请微信登录二维码
            let _this = this;
            new WxLogin({
                id: "weixin",
                appid: "wx67cfaf9e3ad31a0d",  // 这个appid要填死
                scope: "snsapi_login",
                // 扫码成功后重定向的接口
                redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
                // state填写编码后的url
                state: encodeURIComponent(window.btoa("http://127.0.0.1:8080" + _this.$route.path)),
                // 调用样式文件
                href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCg0KLmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGUgew0KICAgIG1hcmdpbi10b3A6IDMwcHg7DQp9",
            });
        },
        countDown(){
            //倒计时的方法
            this.timer = setInterval(()=>{
                this.count--;
                if(this.count==0){
                    clearInterval(this.timer);
                    this.count=this.maxCount;
                    this.isShowCount = false;
                }
            },1000)
        },
        verifyFn(){
            //1 手机号码的验证
            if(!validatePhoneNum(this.phoneNum)){
                // alert("请输入正确的手机号");
                this.asyncChanIsShowToast({
                    msg:"请输入正确的手机号",
                    type:"warning"
                })
                // this.$refs.phone.focus();
                return false
            } 
            // alert("手机号格式正确");
            //2 拼图滑块的验证
            //if(msg 的是再试一次  或者 向右滑动 )
            if(this.msg=='再试一次'|| this.msg== '向右滑动'){
                //就说明用户没有拖拽验证或者验证失败
                // alert("请移动滑块至正确位置")
                this.asyncChanIsShowToast({
                    msg:"请移动滑块至正确位置",
                    type:"warning"
                })
                return false
            }
            return true
        },
        async getSMScode(){
            //获取验证码按钮函数
            // 手机号码与拼图验证
            if(!this.verifyFn())return;
            //验证通过就可以获取验证码 --- 向后端发送请求 ，发送成功就开倒计时
            let res  = await SendSMSAPI({
                phone:this.phoneNum
            })
            // console.log(res)
            if(!res)return;
            //倒计时   显示"获取验证码"或者倒计时
            this.isShowCount=true
            this.countDown()
        },
         // 拼图成功
        onSuccess(times) {
            let ms = (times / 1000).toFixed(1);
            this.msg = "login success, 耗时 " + ms + "s";
        },
        // 拼图失败
        onFail() {
            this.onRefresh(); // 重新刷新拼图
        },
        // 拼图刷新
        onRefresh() {
            this.msg = "再试一次";
        },
        async submitLogin(){
            //点击登录按钮执行这里的代码
            //1 手机号码的验证
            //2 拼图滑块的验证
            // 手机号码与拼图验证
            if(!this.verifyFn())return;
            //3 手机验证码的验证
            if(!this.SMSCode){
                // alert("请输入手机验证码");
                this.asyncChanIsShowToast({
                    msg:"请输入手机验证码",
                    type:"warning"
                })
                return
            }
            
            let uuid = localStorage.getItem('uuid')
            let res=null;
            if(uuid){
                //手机号绑定微信接口的请求
                res = await bingPhoneAPI({
                    verifyCode : this.SMSCode, //手机验证码
                    phone:this.phoneNum,   //手机号
                    uuid
                })
            }else{
                //做普通的登录功能
                res = await PhoneReginAPI({
                    verifyCode : this.SMSCode, //手机验证码
                    phone:this.phoneNum   //手机号
                })
            }
            
            if(!res)return;
            //登录成功后的逻辑
            //1 提示登录成功
            // alert(res.message)
            this.asyncChanIsShowToast({
                    msg:res.message,
                    type:"success"
                })
            //2 关闭登录窗口
            this.chanIsShowLoginModalA(false)
            //3 保存token 值
            localStorage.setItem("x-auth-token",res['x-auth-token'])
            //4 登录状态的切换
            this.chanIsShowCart(true)
            
            // console.log(res);
            //登录成功后之后，删除uuid和地址栏上的code
            if(uuid){
                localStorage.removeItem("uuid");
                this.$router.push(this.$route.path)
            }
            //登录成功之后获取用户信息
            this.asyncCharUserInfo()
        }
    }
}
</script>

<style lang = "less" scoped>
@import url("@/assets/css/global.less");
    .login-modal{
        width: 100%;
        height: 100%;
        position: fixed;
        left: 0;
        top: 0;
        
        .mask{/* 阻止事件冒泡*/
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .login-box{
            width: 555px;
            height: 423px;
            background: url("@/assets/img/login-box-bg.png");
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            .close{
                position: absolute;
                top: 15px;
                right: 55px;
                cursor: pointer;
            }
            .title{
                display: flex;
                justify-content: center;
                padding-top: 40px;
                font-size: 18px;
                color: #cccccc;
                
                :nth-child(2){
                    margin: -2px 10px 0;
                    cursor: auto;
                }
                .active{
                    color: #333333;
                }
                
                li{
                    cursor: pointer;
                }
            }
            
            .body{
                width: 360px;
                height: 200px;
                margin: 25px auto 0;
                /* background-color: #fcf; */
                
                .form{
                    .input-group{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 20px;
                        input{
                            flex: 1;
                            height: 48px;
                            text-indent: 12px;
                            border: 1px solid #cccccc;
                        }
                        .get-code{
                            width: 100px;
                            font-size: 16px;
                            margin-left: 10px;
                            
                            :nth-child(2){
                                display: inline-block;
                                width: 100px;
                                height: 50px;
                                background-color:#cccccc;
                                color: #333333;
                            }
                        }
                    }
                    .btn{
                        background-color: @base-color;
                        height: 50px;
                        color: #fff;
                        font-size: 18px;
                        text-align: center;
                        line-height: 50px;
                    }
                }
                #weixin{
                    /* background-color: #fcf; */
                    display: flex;
                    justify-content: center;
                    margin-top: -20px;
                }
            }
        }
    }
    
    #slideVerify{
        margin-top: -15px;
    }
    /deep/.slide-verify-slider{
        box-sizing:border-box ;
    }
    
    /deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
        position: absolute;
        left: 0;
        top: -120px;
        display: none;
        width: 100%;
        box-sizing: border-box;
    }
    .slide-verify-block{
        width: 85px;
        height: 136px;
    }
    .slide-verify-refresh-icon {
        top: -120px;
        display: none;
    }
    &:hover {
        canvas {
            display: block;
        }
        .slide-verify-refresh-icon {
            display: block;
        }
    }
}
</style>
